<template>
   <section> 
    <el-form class="form" :model="channelGroup" :rules="formRules" 
      ref="channelGroupForm" label-width="80px" label-position="right" size="small">
      <el-form-item label="群组名称" prop="groupName">
        <el-col :span="16"><el-input ref="channelGroupName" size="small" :maxlength="64" v-model="channelGroup.groupName" autofocus="autofocus" @focus="clearValidate"></el-input></el-col>
      </el-form-item>
      <el-form-item label="群组备注" prop="remark">
        <el-col :span="16">
          <el-input type="textarea" :rows="3" v-model="channelGroup.remark">
          </el-input>          
        </el-col>
      </el-form-item>
      <el-form-item label="成员">
        <el-col :span="16">
 			<el-tag
			  :key="user.userid"
			  v-for="(user,index) in channelGroup.users"
			  closable
			  :disable-transitions="false"
			  @close="unselectUser(user,index)">
			  {{user.username?user.username:user.userid}}
			</el-tag> 
			<el-button  class="button-new-tag" size="small" :disabled="showLoading" @click="showUsersSelectDlg">+ 新成员</el-button>
        </el-col>
      </el-form-item>
    </el-form>
  			<!--选中更多用户-->
	<el-dialog title="选择更多用户" :visible.sync="usersSelectVisible"  width="70%"  :close-on-click-modal="false" append-to-body>
		  <users-select :selected-users="channelGroup.users" :visible="usersSelectVisible" @cancel="usersSelectVisible=false" @confirm="afterUsersSelectConfirm"></users-select>
	</el-dialog>
   
    <span slot="footer" class="dialog-footer">
      <el-button size="small" @click="doCloseDialog()">取 消</el-button>
      <el-button type="primary" size="small" :disabled="showLoading" @click="doSaveChannelGroup()">确 定</el-button>
    </span>
    </section>
</template>

<script>
import seq from '@/common/js/sequence';//全局公共库
import { queryGroupAndUsers } from '@/api/mdp/im/group/imGroup'
import UsersSelect from '../../sys/user/UsersSelect.vue'; 
import { mapGetters } from 'vuex'

export default { 
  props:['selectedChannelGroup','visible'],
  name: "create-channel-group",
  computed: { 
	    ...mapGetters([
	      'userInfo','token'
	    ])
  },
  data() {
    return {
      showLoading: false, 
      channelGroup : {
        groupName: '',
        categoryId: '',
        cuserid:'',
        cusername:'',
        bizStatus:'',
        gstatus:'1',
        shopId:'',
        locationId:'',
        branchId:'',
        allowJoin:'1',
        needAudit:'0',
        headimgurl:'',
        isPrichat:'0', 
        sendUserid:'',
        sendUsername:'',
        toUserid:'',
        remark:'',
        users: [], 
      },
      oldUsers:[],//原来的用户
      searchParams: {
        username: '',
        limit: 20,
        offset: 0
      },  
      usersSelectVisible:false, 
      userTotal: 0,
      formRules: {
        name: [
          { required: true, message: '请输入群组名称', trigger: 'blur' },
          { min: 3, max: 64, message: '长度在 3 到 64 个字符', trigger: 'blur' }
        ],
      }      
    }
  },
  methods: {
    doCloseDialog() {
       this.$emit('cancel');
    },
    showUsersSelectDlg(){
      this.usersSelectVisible=true;
      this.getGroupAndUsers();
    },
    clearValidate() {
      this.$refs['channelGroupForm'].clearValidate()
    },
    afterUsersSelectConfirm: function(users){
    	console.log('xxxxxxxxxxxxxxxxxxxxxx')
    	console.log(users)
    	if(!this.channelGroup.users){
    		this.channelGroup.users=[]
    	}
    	users.forEach(user=>{
    		if(!this.channelGroup.users.some(i=>i.userid==user.userid)){
    			this.channelGroup.users.push(Object.assign({},user))
    		}
      }) 
      this.channelGroup.groupName=this.getGroupNameIfNull(this.channelGroup)
    	this.usersSelectVisible=false;
    }, 
    getGroupAndUsers() {
      this.showLoading = true
      queryGroupAndUsers({groupId:this.channelGroup.groupId})
      .then(res => {
        if(res.data.data){
           this.channelGroup=res.data.data
          this.channelGroup.groupName=this.getGroupNameIfNull(this.channelGroup)
          this.oldUsers=[].concat(this.channelGroup.users);
        }
       
        this.showLoading=false;
      })
      .catch(error => {
        this.showLoading = false
        //outputError(this, error)
      })      
    }, 
    getGroupNameIfNull(channelGroup){
      if(channelGroup.groupName==''||channelGroup.groupName==null||channelGroup.groupName.indexOf(this.userInfo.username)==0){
    		var users=channelGroup.users;
        var groupName='';
        if(users==null || users.length==0){
          if(channelGroup.isPrichat!='1'){
            if(channelGroup.cuserid&&channelGroup.cuserid!=this.userInfo.userid){
              groupName=channelGroup.cusername?channelGroup.cusername:channelGroup.cuserid+"创建的群聊"
            }else{
              groupName=this.userInfo.username+"创建的群聊"
            } 
          }else{
              if(channelGroup.sendUserid&&channelGroup.sendUserid!=this.userInfo.userid){
                 groupName=channelGroup.sendUsername?channelGroup.sendUsername:channelGroup.sendUserid+"创建的聊天"
              }else{
                groupName=this.userInfo.username+"创建的聊天"
              }
             
          }
        }else{
          if(users.length>3){
            groupName=(users[0].username?users[0].username:users[0].userid)+','+(users[1].username?users[1].username:users[1].userid)+','+(users[2].username?users[2].username:users[2].userid)
          }else{
            groupName=users.map(i=>i.username?i.username:i.userid).join(",");
          }
          groupName=groupName+"等参与的群聊"
        }
    		return groupName
    	}else{
        return channelGroup.groupName
      }
    },
    unselectUser: function(user,index) {
    	console.log(user)
      if(user.userid !== this.userInfo.userid) {   
            this.channelGroup.users.splice(index, 1); 
            this.channelGroup.groupName=this.getGroupNameIfNull(this.channelGroup)
      }  
    },
    loadMoreUser() {
      this.searchParams.offset += this.searchParams.limit
      this.getGroupAndUsers()
    },
    doSaveChannelGroup() {
      this.$refs['channelGroupForm'].validate(valid => {
        if (valid) {  
          //this.channelGroup.groupId=seq.sn();
            if(this.selectedChannelGroup.groupName!=this.channelGroup.groupName){
              this.$emit('saveGroupName',this.channelGroup)
            } 
            let oldUsers=this.oldUsers;
            let newUsers=this.channelGroup.users;
            let leaveChannelGroupUsers=oldUsers.filter(i=>!newUsers.some(k=>k.userid==i.userid))
            let joinChannelGroupUsers=newUsers.filter(i=>!oldUsers.some(k=>k.userid==i.userid))
            if(leaveChannelGroupUsers.length>0){
              let groupUsers={
                groupId:this.channelGroup.groupId,
                groupName:this.channelGroup.groupName,
                users:leaveChannelGroupUsers
              }
              this.$emit('leaveChannelGroup',groupUsers)
            }
            if(joinChannelGroupUsers.length>0){
              let groupUsers={
                groupId:this.channelGroup.groupId,
                groupName:this.channelGroup.groupName,
                users:joinChannelGroupUsers
              }
              this.$emit('joinChannelGroup',groupUsers)
            }
            this.channelGroup.isPrichat="0"
            this.$emit("confirm",this.channelGroup);
            this.showLoading = false
            this.doCloseDialog();
           // Object.assign(this.$data, this.$options.data())
            //this.dialogProps.visible = false
        }
      })
    },
    doSearchUser() { 
      this.getGroupAndUsers()
    },
    onSearchInputKeyUp(event) {
      if(event.keyCode === 13) { 
        this.getGroupAndUsers()
      }
    }     
  },
  watch: {
    'visible': function(visible) {
          if(visible==true) {  
              console.log("喝杯咖啡。。。。。。。。。。。。。。。。。。。")
            if(this.selectedChannelGroup) { 
                if(this.selectedChannelGroup.users){
                  this.oldUsers=this.selectedChannelGroup.users;
                }else{
                  this.oldUsers=[];
                }
                
                this.channelGroup=Object.assign({},this.selectedChannelGroup); 
            
            }
          this.$nextTick(()=>{
            this.getGroupAndUsers(); 
          })
          
      }
    }, 
    'selectedChannelGroup': function(selectedChannelGroup) {
       console.log("喝杯奶茶。。。。。。。。。。。。。。。。。。。")
       console.log(selectedChannelGroup)
     
    }, 
  },  
	components: {  
	    'users-select':UsersSelect,  
	    //在下面添加其它组件
	},
  mounted: function() { 
    this.oldUsers=[]
    if(!this.selectedChannelGroup){
      return;
    }
    this.channelGroup=Object.assign({},this.selectedChannelGroup )
	  this.getGroupAndUsers();
  }
}
</script>

<style lang="scss" scoped>
.form {
  padding: 2px 0 0 16px;
  border-bottom: solid 1px #F0EEEA;
}
.user-list-container {
  border: solid 1px #D4D1CC;
  width: 48%;
  .title {
    height: 32px;
    text-align: center;
    font-weight: bold;
    background-color: #F0F0F0;
    border-bottom: solid 1px #F0F0F0;
  }
  .search-container {
    text-align: center;
    padding: 0;
    margin: 0;
    border-bottom: solid 1px #F0F0F0;
    input {
      margin: 0 0 0 4px;
      height: 22px;
      line-height: 22px;
      width: 110px;
      outline: 0;
      border: none;
      background-color: transparent;
      -webkit-appearance: textfield;
      -webkit-rtl-ordering: logical;
      cursor: text;
    }
    i {
      cursor: pointer;
      height: 22px;
      line-height: 22px;
    }    
    input::-webkit-input-placeholder {
      color: #DDDBD7;
    }
    input::-moz-placeholder {   /* Mozilla Firefox 19+ */
      color: #DDDBD7;
    }
    input:-moz-placeholder {    /* Mozilla Firefox 4 to 18 */
      color: #DDDBD7;
    }
    input:-ms-input-placeholder {  /* Internet Explorer 10-11 */ 
      color: #DDDBD7;
    }      
  }
  ul {
    padding: 0;
    margin: 0;
    overflow-y: auto;
    list-style-type: none;
    .load-more {
      text-align: center;
      font-size: 11px;
    }
    li {
      display: list-item;
      padding: 0 5px;
      margin: 0;
      span {
        font-weight: bold;
        float: right;
        display: none;
      }
    }
    li:hover {
      background-color: #F1EFEE;
      cursor: pointer;
    }
    li:hover span {
      display: block;
    }    
  }
}
.left-list {
  float: left;
  ul {
    height: 200px;
  }
}
.right-list {
  float: right;
  ul {
    height: 232px;
  }  
}
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  } 
</style>